package com.ray.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProviderLock {

        /**
         * 生产者消费者
         * 2个生产者生产汉堡，2个消费者消费汉堡
         *
         * 任务用sleep 资源用wait
         */

        public static void main(String[] args) {
            final Data2 data = new Data2();
            new Thread(new Runnable() {
                public void run() {
                    for (int i=0;i<30;i++){
                        data.increment();
                    }
                }
            },"A").start();
            new Thread(new Runnable() {
                public void run() {
                    for (int i=0;i<30;i++){
                        data.decrement();
                    }
                }
            },"B").start();

        }


    }

    class Data2{
        private int num=0;//个数
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        public void increment(){
            lock.lock();
            while(num!=0){
                try {
//                    this.wait();//lock不能用wait
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            num++;
//            this.notify();//lock不能用notify
            condition.signal();
            System.out.println(Thread.currentThread().getName()+"生产了第"+num+"个汉堡");
            lock.unlock();
        }

        public void decrement(){
            lock.lock();
            while(num==0){
                try {
                    //                    this.wait();//lock不能用wait
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //            this.notify();//lock不能用notify
            condition.signal();
            System.out.println(Thread.currentThread().getName()+"消费了第"+num+"个汉堡");
            num--;
            lock.unlock();
        }
    }

